{% extends "base.html" %}

{% block title %}角色管理 - 梦幻西游数字资产管理系统{% endblock %}

{% block mobile_title %}角色管理{% endblock %}

{% block content %}
<div class="container-fluid roles-page">
    <div class="row mb-4">
        <div class="col-md-6">
            <h2 class="page-title">🎮 角色管理</h2>
        </div>
        <div class="col-md-6 text-md-end">
            <button class="btn btn-primary" onclick="showAddRoleModal()">
                <i class="bi bi-plus-circle me-2"></i>添加角色
            </button>
        </div>
    </div>
    
    <!-- 高级查询 -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="mb-0">
                <i class="bi bi-funnel me-2"></i>高级查询
                <button class="btn btn-sm btn-link float-end" type="button" data-bs-toggle="collapse" data-bs-target="#advancedSearch">
                    <i class="bi bi-chevron-down"></i>
                </button>
            </h6>
        </div>
        <div class="card-body collapse show" id="advancedSearch">
            <div class="row g-3">
                <div class="col-md-2">
                    <label class="form-label small">顺序（最小）</label>
                    <input type="number" class="form-control" id="searchOrderMin" placeholder="最小值">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">顺序（最大）</label>
                    <input type="number" class="form-control" id="searchOrderMax" placeholder="最大值">
                </div>
                <div class="col-md-3">
                    <label class="form-label small">角色名</label>
                    <input type="text" class="form-control" id="searchRole" placeholder="搜索角色名...">
                </div>
                <div class="col-md-3">
                    <label class="form-label small">账号名</label>
                    <input type="text" class="form-control" id="searchAccount" placeholder="搜索账号名...">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">状态</label>
                    <select class="form-select" id="filterStatus">
                        <option value="">全部状态</option>
                        <option value="在用">在用</option>
                        <option value="休息">休息</option>
                        <option value="待删">待删</option>
                    </select>
                </div>
            </div>
            <div class="row g-3 mt-2">
                <div class="col-md-2">
                    <label class="form-label small">等级（最小）</label>
                    <input type="number" class="form-control" id="searchLevelMin" placeholder="最小等级">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">等级（最大）</label>
                    <input type="number" class="form-control" id="searchLevelMax" placeholder="最大等级">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">门派</label>
                    <select class="form-select" id="filterFaction">
                        <option value="">全部门派</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">服务器</label>
                    <select class="form-select" id="filterServer">
                        <option value="">全部服务器</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">角色作用</label>
                    <select class="form-select" id="filterFunction">
                        <option value="">全部作用</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">帮派名称</label>
                    <input type="text" class="form-control" id="searchBangpai" placeholder="搜索帮派...">
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-12 text-end">
                    <button class="btn btn-outline-secondary me-2" onclick="resetSearch()">
                        <i class="bi bi-x-circle me-1"></i>重置
                    </button>
                    <button class="btn btn-primary" onclick="loadRoles()">
                        <i class="bi bi-search me-1"></i>查询
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 角色列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th onclick="sortTable('order')" style="cursor:pointer;">
                                顺序 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th onclick="sortTable('role_name')" style="cursor:pointer;">
                                角色名 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th>账号</th>
                            <th onclick="sortTable('role_level')" style="cursor:pointer;">
                                等级 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th onclick="sortTable('role_faction')" style="cursor:pointer;">
                                门派 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th onclick="sortTable('server_name')" style="cursor:pointer;">
                                服务器 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th>角色作用</th>
                            <th onclick="sortTable('status')" style="cursor:pointer;">
                                状态 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th>房屋</th>
                            <th onclick="sortTable('role_money')" style="cursor:pointer;">
                                金币 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th>仙玉</th>
                            <th style="width: 150px;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="roleTableBody">
                        <tr>
                            <td colspan="12" class="text-center">
                                <div class="spinner-border text-primary my-3" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑角色模态框 -->
<div class="modal fade" id="roleModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="roleModalTitle">➕ 添加新角色</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="roleForm">
                    <input type="hidden" id="editRoleId" value="">
                    
                    <!-- 基本信息 -->
                    <h6 class="border-bottom pb-2 mb-3">📋 基本信息</h6>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">所属账号 *</label>
                            <select class="form-select" id="roleAccountId" required>
                                <option value="">请选择账号</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">角色名称 *</label>
                            <input type="text" class="form-control" id="roleName" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">角色等级</label>
                            <input type="number" class="form-control" id="roleLevel" value="0" min="0" max="175">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">角色门派</label>
                            <select class="form-select" id="roleFaction">
                                <option value="">请选择</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">服务器名称</label>
                            <select class="form-select" id="roleServer">
                                <option value="">请选择</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">角色作用（可多选）</label>
                            <select class="form-select" id="roleFunction" multiple size="4">
                                <option value="">请选择</option>
                            </select>
                            <small class="text-muted">按住 Ctrl 键可多选</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">角色状态</label>
                            <select class="form-select" id="roleStatus">
                                <option value="在用">在用</option>
                                <option value="休息">休息</option>
                                <option value="待删">待删</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">帮派名称</label>
                            <input type="text" class="form-control" id="roleBangpai">
                        </div>
                    </div>

                    <!-- 任务信息 -->
                    <h6 class="border-bottom pb-2 mb-3 mt-4">📝 任务信息</h6>
                    <div class="row">
                        <div class="col-12 mb-3">
                            <label class="form-label">任务类型（可多选）</label>
                            <select class="form-select" id="roleTaskType" multiple size="5">
                            </select>
                            <small class="text-muted">按住 Ctrl 键可多选</small>
                        </div>
                    </div>

                    <!-- 房屋信息 -->
                    <h6 class="border-bottom pb-2 mb-3 mt-4">🏠 房屋信息</h6>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">房屋等级（规模）</label>
                            <select class="form-select" id="roleHouseLevel">
                                <option value="">请选择</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">房屋风水</label>
                            <select class="form-select" id="roleHousePosition">
                                <option value="">请选择</option>
                            </select>
                        </div>
                    </div>

                    <!-- 安全信息 -->
                    <h6 class="border-bottom pb-2 mb-3 mt-4">🔐 安全信息</h6>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">将军令</label>
                            <select class="form-select" id="roleJiangjunling">
                                <option value="">请选择</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">五色旗盒</label>
                            <select class="form-select" id="roleWuseqihe">
                                <option value="0">无</option>
                                <option value="1">有</option>
                            </select>
                        </div>
                    </div>

                    <!-- 生活技能 -->
                    <h6 class="border-bottom pb-2 mb-3 mt-4">🛠️ 生活技能等级</h6>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label">烹饪技巧</label>
                            <input type="number" class="form-control" id="rolePengrenLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">中药医理</label>
                            <input type="number" class="form-control" id="roleZhongyaoLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">巧匠之术</label>
                            <input type="number" class="form-control" id="roleQiaojiangLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">强身术</label>
                            <input type="number" class="form-control" id="roleQiangshenLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">冥想</label>
                            <input type="number" class="form-control" id="roleMingxiangLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">暗器技巧</label>
                            <input type="number" class="form-control" id="roleAnqiLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">打造技巧</label>
                            <input type="number" class="form-control" id="roleDazaoLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">裁缝技巧</label>
                            <input type="number" class="form-control" id="roleCaifengLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">炼金术</label>
                            <input type="number" class="form-control" id="roleLianjinLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">逃离技巧</label>
                            <input type="number" class="form-control" id="roleTaoliLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">追捕技巧</label>
                            <input type="number" class="form-control" id="roleZhuibuLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">养生之道</label>
                            <input type="number" class="form-control" id="roleYangshengLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">健身术</label>
                            <input type="number" class="form-control" id="roleJianshenLevel" value="0" min="0" max="160">
                        </div>
                    </div>
                    
                    <!-- 剧情技能 -->
                    <h6 class="border-bottom pb-2 mb-3 mt-4">📖 剧情技能等级</h6>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label">调息</label>
                            <input type="number" class="form-control" id="roleTiaxiLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">打坐</label>
                            <input type="number" class="form-control" id="roleDazuoLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">丹元济会</label>
                            <input type="number" class="form-control" id="roleDanyuanLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">妙手空空</label>
                            <input type="number" class="form-control" id="roleMiaoshouLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">宝石工艺</label>
                            <input type="number" class="form-control" id="roleBaoshiLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">奇门遁甲</label>
                            <input type="number" class="form-control" id="roleQimenLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">古董评估</label>
                            <input type="number" class="form-control" id="roleGudongLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">仙灵店铺</label>
                            <input type="number" class="form-control" id="roleXianlingLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">建筑之术</label>
                            <input type="number" class="form-control" id="roleJianzhuLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">变化之术</label>
                            <input type="number" class="form-control" id="roleBianhuaLevel" value="0" min="0" max="160">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">火眼金睛</label>
                            <input type="number" class="form-control" id="roleHuoyanLevel" value="0" min="0" max="160">
                        </div>
                    </div>

                    <!-- 资产信息 -->
                    <h6 class="border-bottom pb-2 mb-3 mt-4">💰 资产信息</h6>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">角色金币（梦幻币）</label>
                            <input type="number" class="form-control" id="roleMoney" value="0" min="0">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">仙玉数量</label>
                            <input type="number" class="form-control" id="roleXianyu" value="0" min="0">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">金币数量（点卡金币）</label>
                            <input type="number" class="form-control" id="roleJinbi" value="0" min="0">
                        </div>
                    </div>

                    <!-- 其他信息 -->
                    <h6 class="border-bottom pb-2 mb-3 mt-4">📊 其他信息</h6>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">宠物数量</label>
                            <input type="number" class="form-control" id="rolePetCount" value="0" min="0">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">装备评分</label>
                            <input type="number" class="form-control" id="roleZhuangbeiScore" value="0" min="0">
                        </div>
                        <div class="col-12 mb-3">
                            <label class="form-label">备注信息</label>
                            <textarea class="form-control" id="roleRemarks" rows="3"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveRole()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 查看角色详情模态框 -->
<div class="modal fade" id="roleDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailModalTitle">角色详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="roleDetailBody">
                <!-- 详情内容 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let roleModal = null;
let roleDetailModal = null;
let configData = {};
let currentEditId = null;
let currentPage = 1;
let perPage = 50;
let sortField = 'order';
let sortOrder = 'asc';

$(document).ready(function() {
    roleModal = new bootstrap.Modal(document.getElementById('roleModal'));
    roleDetailModal = new bootstrap.Modal(document.getElementById('roleDetailModal'));
    loadConfig();
    loadRoles();
});

// 加载配置数据
async function loadConfig() {
    try {
        const data = await apiRequest('/api/config');
        configData = data.data;
        
        // 填充账号下拉
        const accounts = await apiRequest('/api/accounts');
        let accountOptions = '<option value="">请选择账号</option>';
        accounts.data.forEach(acc => {
            accountOptions += `<option value="${acc.id}">${acc.account}</option>`;
        });
        $('#roleAccountId').html(accountOptions);
        
        // 填充门派下拉
        let menpaiOptions = '<option value="">请选择</option>';
        configData.menpai.forEach(m => {
            menpaiOptions += `<option value="${m.name}">${m.name} (${m.race})</option>`;
        });
        $('#roleFaction, #filterFaction').html(menpaiOptions);
        $('#filterFaction').prepend('<option value="">全部门派</option>');
        
        // 填充服务器下拉
        let serverOptions = '<option value="">请选择</option>';
        configData.servers.forEach(s => {
            serverOptions += `<option value="${s.name}">${s.name}</option>`;
        });
        $('#roleServer, #filterServer').html(serverOptions);
        $('#filterServer').prepend('<option value="">全部服务器</option>');
        
        // 填充任务类型（多选）
        let taskOptions = '';
        configData.tasks.forEach(t => {
            taskOptions += `<option value="${t.task_name}">${t.task_name} (${t.task_type})</option>`;
        });
        $('#roleTaskType').html(taskOptions);
        
        // 填充将军令下拉
        let jjlOptions = '<option value="">请选择</option>';
        configData.jiangjunling.forEach(j => {
            const displayText = j.device ? `${j.phone} (${j.device})` : j.phone;
            jjlOptions += `<option value="${j.phone}">${displayText}</option>`;
        });
        $('#roleJiangjunling').html(jjlOptions);
        
        // 填充房屋等级下拉
        let houseScaleOptions = '<option value="">请选择</option>';
        configData.house_scales.forEach(h => {
            houseScaleOptions += `<option value="${h}">${h}</option>`;
        });
        $('#roleHouseLevel').html(houseScaleOptions);
        
        // 填充风水等级下拉
        let fengShuiOptions = '<option value="">请选择</option>';
        configData.feng_shui.forEach(f => {
            fengShuiOptions += `<option value="${f}">${f}</option>`;
        });
        $('#roleHousePosition').html(fengShuiOptions);
        
        // 填充角色作用下拉
        let roleFuncOptions = '<option value="">请选择</option>';
        configData.role_functions.forEach(rf => {
            roleFuncOptions += `<option value="${rf.role_function}">${rf.role_function}</option>`;
        });
        $('#roleFunction, #filterFunction').html(roleFuncOptions);
        $('#filterFunction').prepend('<option value="">全部作用</option>');
        
    } catch (error) {
        console.error('加载配置失败:', error);
        showNotification('加载配置失败，请刷新页面', 'error');
    }
}

// 加载角色列表
async function loadRoles() {
    try {
        // 获取所有查询条件
        const searchRole = $('#searchRole').val().trim();
        const searchAccount = $('#searchAccount').val().trim();
        const filterStatus = $('#filterStatus').val();
        const filterFaction = $('#filterFaction').val();
        const filterServer = $('#filterServer').val();
        const filterFunction = $('#filterFunction').val();
        const searchBangpai = $('#searchBangpai').val().trim();
        const searchOrderMin = $('#searchOrderMin').val().trim();
        const searchOrderMax = $('#searchOrderMax').val().trim();
        const searchLevelMin = $('#searchLevelMin').val().trim();
        const searchLevelMax = $('#searchLevelMax').val().trim();
        
        // 构建查询参数
        const params = new URLSearchParams({
            page: currentPage,
            per_page: perPage,
            sort_field: sortField,
            sort_order: sortOrder
        });
        
        // 添加查询条件
        if (searchRole) params.append('role_name', searchRole);
        if (searchAccount) params.append('account_name', searchAccount);
        if (filterStatus) params.append('status', filterStatus);
        if (filterFaction) params.append('role_faction', filterFaction);
        if (filterServer) params.append('server_name', filterServer);
        if (filterFunction) params.append('role_function', filterFunction);
        if (searchBangpai) params.append('bangpai_name', searchBangpai);
        if (searchOrderMin) params.append('order_min', searchOrderMin);
        if (searchOrderMax) params.append('order_max', searchOrderMax);
        if (searchLevelMin) params.append('level_min', searchLevelMin);
        if (searchLevelMax) params.append('level_max', searchLevelMax);
        
        const data = await apiRequest(`/api/roles?${params.toString()}`);
        const roles = data.data;
        
        if (roles.length === 0) {
            $('#roleTableBody').html(`
                <tr>
                    <td colspan="12" class="text-center py-4">
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <p>没有找到匹配的角色</p>
                        </div>
                    </td>
                </tr>
            `);
            return;
        }
        
        let html = '';
        roles.forEach(role => {
            const statusBadge = getStatusBadge(role.status);
            const factionDisplay = role.role_faction || '-';
            const serverDisplay = role.server_name || '-';
            
            // 角色作用显示（多选，用徽章展示）
            let functionDisplay = '-';
            if (role.role_function) {
                const functions = role.role_function.split(',').map(f => f.trim()).filter(f => f);
                if (functions.length > 0) {
                    functionDisplay = functions.map(f => `<span class="badge bg-info me-1">${f}</span>`).join('');
                }
            }
            
            const houseDisplay = role.house_level ? `${role.house_level}(${role.house_position || '-'})` : '-';
            
            html += `
                <tr>
                    <td><strong>${role.order || 0}</strong></td>
                    <td><strong>${role.role_name}</strong></td>
                    <td>${role.account_name}</td>
                    <td><span class="badge bg-primary">Lv.${role.role_level}</span></td>
                    <td>${factionDisplay}</td>
                    <td>${serverDisplay}</td>
                    <td>${functionDisplay}</td>
                    <td>${statusBadge}</td>
                    <td>${houseDisplay}</td>
                    <td>${formatMoney(role.role_money)}</td>
                    <td>${role.role_xianyu}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-info" onclick="viewRoleDetail('${role.id}')" title="查看详情">
                            <i class="bi bi-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-primary" onclick="editRole('${role.id}')" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteRole('${role.id}')" title="删除">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        $('#roleTableBody').html(html);
        
        // 显示分页信息
        if (data.total > perPage) {
            console.log(`显示第 ${currentPage} 页，共 ${data.pages} 页，总计 ${data.total} 条记录`);
        }
    } catch (error) {
        console.error('加载角色列表失败:', error);
        $('#roleTableBody').html('<tr><td colspan="12" class="text-center text-danger">加载失败</td></tr>');
    }
}

// 显示添加角色模态框
function showAddRoleModal() {
    currentEditId = null;
    $('#roleModalTitle').text('➕ 添加新角色');
    $('#editRoleId').val('');
    $('#roleForm')[0].reset();
    $('#roleStatus').val('在用');
    $('#roleTaskType').val([]);
    $('#roleFunction').val([]);
    roleModal.show();
}

// 编辑角色
async function editRole(id) {
    try {
        const data = await apiRequest('/api/roles');
        const role = data.data.find(r => r.id === id);
        
        if (!role) {
            showNotification('角色不存在', 'error');
            return;
        }
        
        currentEditId = id;
        $('#roleModalTitle').text('✏️ 编辑角色');
        $('#editRoleId').val(id);
        
        // 填充表单
        $('#roleAccountId').val(role.account_id);
        $('#roleName').val(role.role_name);
        $('#roleLevel').val(role.role_level);
        $('#roleFaction').val(role.role_faction || '');
        $('#roleServer').val(role.server_name || '');
        
        // 角色作用（多选）
        if (role.role_function) {
            const functions = role.role_function.split(',').map(f => f.trim());
            $('#roleFunction').val(functions);
        } else {
            $('#roleFunction').val([]);
        }
        
        $('#roleStatus').val(role.status);
        $('#roleBangpai').val(role.bangpai_name || '');
        
        // 任务类型（多选）
        if (role.task_type) {
            const tasks = role.task_type.split(',').map(t => t.trim());
            $('#roleTaskType').val(tasks);
    } else {
            $('#roleTaskType').val([]);
        }
        
        $('#roleHouseLevel').val(role.house_level || '');
        $('#roleHousePosition').val(role.house_position || '');
        $('#roleJiangjunling').val(role.jiang_jun_ling || '');
        $('#roleWuseqihe').val(role.wuseqihe ? '1' : '0');
        
        // 生活技能
        $('#rolePengrenLevel').val(role.pengren_level || 0);
        $('#roleZhongyaoLevel').val(role.zhongyao_level || 0);
        $('#roleQiaojiangLevel').val(role.qiaojiang_level || 0);
        $('#roleQiangshenLevel').val(role.qiangshen_level || 0);
        $('#roleMingxiangLevel').val(role.mingxiang_level || 0);
        $('#roleAnqiLevel').val(role.anqi_level || 0);
        $('#roleDazaoLevel').val(role.dazao_level || 0);
        $('#roleCaifengLevel').val(role.caifeng_level || 0);
        $('#roleLianjinLevel').val(role.lianjin_level || 0);
        $('#roleTaoliLevel').val(role.taoli_level || 0);
        $('#roleZhuibuLevel').val(role.zhuibu_level || 0);
        $('#roleYangshengLevel').val(role.yangsheng_level || 0);
        $('#roleJianshenLevel').val(role.jianshen_level || 0);
        
        // 剧情技能
        $('#roleTiaxiLevel').val(role.tiaxi_level || 0);
        $('#roleDazuoLevel').val(role.dazuo_level || 0);
        $('#roleDanyuanLevel').val(role.danyuan_level || 0);
        $('#roleMiaoshouLevel').val(role.miaoshou_level || 0);
        $('#roleBaoshiLevel').val(role.baoshi_level || 0);
        $('#roleQimenLevel').val(role.qimen_level || 0);
        $('#roleGudongLevel').val(role.gudong_level || 0);
        $('#roleXianlingLevel').val(role.xianling_level || 0);
        $('#roleJianzhuLevel').val(role.jianzhu_level || 0);
        $('#roleBianhuaLevel').val(role.bianhua_level || 0);
        $('#roleHuoyanLevel').val(role.huoyan_level || 0);
        
        $('#roleMoney').val(role.role_money);
        $('#roleXianyu').val(role.role_xianyu);
        $('#roleJinbi').val(role.role_jinbi);
        
        $('#rolePetCount').val(role.pet_count);
        $('#roleZhuangbeiScore').val(role.zhuangbei_score);
        $('#roleRemarks').val(role.remarks || '');
        
        roleModal.show();
    } catch (error) {
        console.error('加载角色数据失败:', error);
        showNotification('加载角色数据失败', 'error');
    }
}

// 保存角色
async function saveRole() {
    const form = document.getElementById('roleForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // 获取任务类型（多选）
    const selectedTasks = $('#roleTaskType').val() || [];
    const taskTypeStr = selectedTasks.join(',');
    
    // 获取角色作用（多选）
    const selectedFunctions = $('#roleFunction').val() || [];
    const roleFunctionStr = selectedFunctions.filter(f => f !== '').join(',');
    
    const data = {
        account_id: $('#roleAccountId').val(),
        role_name: $('#roleName').val(),
        role_level: parseInt($('#roleLevel').val()) || 0,
        role_faction: $('#roleFaction').val(),
        server_name: $('#roleServer').val(),
        role_function: roleFunctionStr,
        status: $('#roleStatus').val(),
        bangpai_name: $('#roleBangpai').val(),
        task_type: taskTypeStr,
        house_level: $('#roleHouseLevel').val(),
        house_position: $('#roleHousePosition').val(),
        jiang_jun_ling: $('#roleJiangjunling').val(),
        wuseqihe: $('#roleWuseqihe').val() === '1',
        // 生活技能
        pengren_level: parseInt($('#rolePengrenLevel').val()) || 0,
        zhongyao_level: parseInt($('#roleZhongyaoLevel').val()) || 0,
        qiaojiang_level: parseInt($('#roleQiaojiangLevel').val()) || 0,
        qiangshen_level: parseInt($('#roleQiangshenLevel').val()) || 0,
        mingxiang_level: parseInt($('#roleMingxiangLevel').val()) || 0,
        anqi_level: parseInt($('#roleAnqiLevel').val()) || 0,
        dazao_level: parseInt($('#roleDazaoLevel').val()) || 0,
        caifeng_level: parseInt($('#roleCaifengLevel').val()) || 0,
        lianjin_level: parseInt($('#roleLianjinLevel').val()) || 0,
        taoli_level: parseInt($('#roleTaoliLevel').val()) || 0,
        zhuibu_level: parseInt($('#roleZhuibuLevel').val()) || 0,
        yangsheng_level: parseInt($('#roleYangshengLevel').val()) || 0,
        jianshen_level: parseInt($('#roleJianshenLevel').val()) || 0,
        // 剧情技能
        tiaxi_level: parseInt($('#roleTiaxiLevel').val()) || 0,
        dazuo_level: parseInt($('#roleDazuoLevel').val()) || 0,
        danyuan_level: parseInt($('#roleDanyuanLevel').val()) || 0,
        miaoshou_level: parseInt($('#roleMiaoshouLevel').val()) || 0,
        baoshi_level: parseInt($('#roleBaoshiLevel').val()) || 0,
        qimen_level: parseInt($('#roleQimenLevel').val()) || 0,
        gudong_level: parseInt($('#roleGudongLevel').val()) || 0,
        xianling_level: parseInt($('#roleXianlingLevel').val()) || 0,
        jianzhu_level: parseInt($('#roleJianzhuLevel').val()) || 0,
        bianhua_level: parseInt($('#roleBianhuaLevel').val()) || 0,
        huoyan_level: parseInt($('#roleHuoyanLevel').val()) || 0,
        role_money: parseInt($('#roleMoney').val()) || 0,
        role_xianyu: parseInt($('#roleXianyu').val()) || 0,
        role_jinbi: parseInt($('#roleJinbi').val()) || 0,
        pet_count: parseInt($('#rolePetCount').val()) || 0,
        zhuangbei_score: parseInt($('#roleZhuangbeiScore').val()) || 0,
        remarks: $('#roleRemarks').val()
    };
    
    try {
        if (currentEditId) {
            // 更新
            await apiRequest(`/api/roles/${currentEditId}`, {
                method: 'PUT',
                body: JSON.stringify(data)
            });
            showNotification('角色更新成功');
        } else {
            // 新增
        await apiRequest('/api/roles', {
            method: 'POST',
            body: JSON.stringify(data)
        });
            showNotification('角色添加成功');
        }
        
        roleModal.hide();
        loadRoles();
    } catch (error) {
        console.error('保存角色失败:', error);
        showNotification('保存失败: ' + error.message, 'error');
    }
}

// 查看角色详情
async function viewRoleDetail(id) {
    try {
        const data = await apiRequest('/api/roles');
        const role = data.data.find(r => r.id === id);
        
        if (!role) {
            showNotification('角色不存在', 'error');
            return;
        }
        
        $('#detailModalTitle').text(`角色详情 - ${role.role_name}`);
        
        // 角色作用显示（多选）
        let functionDisplay = '-';
        if (role.role_function) {
            const functions = role.role_function.split(',').map(f => f.trim()).filter(f => f);
            if (functions.length > 0) {
                functionDisplay = functions.map(f => `<span class="badge bg-info me-1">${f}</span>`).join('');
            }
        }
        
        const html = `
            <div class="row">
                <div class="col-md-6 mb-3">
                    <strong>账号：</strong>${role.account_name}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>角色名：</strong>${role.role_name}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>等级：</strong>${role.role_level}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>门派：</strong>${role.role_faction || '-'}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>服务器：</strong>${role.server_name || '-'}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>角色作用：</strong>${functionDisplay}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>状态：</strong>${getStatusBadge(role.status)}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>帮派：</strong>${role.bangpai_name || '-'}
                </div>
                <div class="col-12 mb-3">
                    <strong>任务类型：</strong>${role.task_type || '-'}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>房屋等级：</strong>${role.house_level || '-'}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>房屋风水：</strong>${role.house_position || '-'}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>将军令：</strong>${role.jiang_jun_ling || '-'}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>五色旗盒：</strong>${role.wuseqihe ? '有' : '无'}
                </div>
                <div class="col-md-4 mb-3">
                    <strong>烹饪等级：</strong>${role.pengren_level}
                </div>
                <div class="col-md-4 mb-3">
                    <strong>炼药等级：</strong>${role.lianyao_level}
                </div>
                <div class="col-md-4 mb-3">
                    <strong>家具等级：</strong>${role.jiajv_level}
                </div>
                <div class="col-md-4 mb-3">
                    <strong>金币：</strong>${formatMoney(role.role_money)}
                </div>
                <div class="col-md-4 mb-3">
                    <strong>仙玉：</strong>${role.role_xianyu}
                </div>
                <div class="col-md-4 mb-3">
                    <strong>金币（点卡）：</strong>${role.role_jinbi}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>宠物数量：</strong>${role.pet_count}
                </div>
                <div class="col-md-6 mb-3">
                    <strong>装备评分：</strong>${role.zhuangbei_score}
                </div>
                <div class="col-12 mb-3">
                    <strong>备注：</strong>${role.remarks || '-'}
                </div>
            </div>
        `;
        
        $('#roleDetailBody').html(html);
        roleDetailModal.show();
    } catch (error) {
        console.error('加载角色详情失败:', error);
        showNotification('加载角色详情失败', 'error');
    }
}

// 删除角色
async function deleteRole(id) {
    if (!confirm('确定要删除这个角色吗？')) {
        return;
    }
    
    try {
        await apiRequest(`/api/roles/${id}`, { method: 'DELETE' });
        showNotification('角色删除成功');
        loadRoles();
    } catch (error) {
        console.error('删除角色失败:', error);
        showNotification('删除失败: ' + error.message, 'error');
    }
}

// 状态徽章
function getStatusBadge(status) {
    const badges = {
        '在用': '<span class="badge bg-success">在用</span>',
        '休息': '<span class="badge bg-warning">休息</span>',
        '待删': '<span class="badge bg-danger">待删</span>'
    };
    return badges[status] || `<span class="badge bg-secondary">${status}</span>`;
}

// 格式化金币
function formatMoney(money) {
    if (!money) return '0';
    return money.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// 重置搜索
function resetSearch() {
    $('#searchRole').val('');
    $('#searchAccount').val('');
    $('#filterStatus').val('');
    $('#filterFaction').val('');
    $('#filterServer').val('');
    $('#filterFunction').val('');
    $('#searchBangpai').val('');
    $('#searchOrderMin').val('');
    $('#searchOrderMax').val('');
    $('#searchLevelMin').val('');
    $('#searchLevelMax').val('');
    currentPage = 1;
    loadRoles();
}

// 回车搜索 - 绑定所有输入框
$('#searchRole, #searchAccount, #searchBangpai, #searchOrderMin, #searchOrderMax, #searchLevelMin, #searchLevelMax').on('keypress', function(e) {
    if (e.key === 'Enter') {
        loadRoles();
    }
});

// 下拉框改变时自动搜索
$('#filterStatus, #filterFunction, #filterFaction, #filterServer').on('change', function() {
    loadRoles();
});

// 排序表格
function sortTable(field) {
    if (sortField === field) {
        // 同一字段切换升序/降序
        sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
    } else {
        // 新字段默认升序
        sortField = field;
        sortOrder = 'asc';
    }
    currentPage = 1;
    loadRoles();
}
</script>
{% endblock %}